package manager
{
	import com.maclema.mysql.Connection;
	import com.maclema.mysql.MySqlToken;
	import com.maclema.mysql.ResultSet;
	import com.maclema.mysql.Statement;
	import com.maclema.mysql.events.MySqlErrorEvent;
	import com.maclema.mysql.events.MySqlEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	
	public class DBConnector
	{
		private static var _instance:DBConnector;
		private var resultAc:ArrayCollection = new ArrayCollection();
		private var con:Connection;
		private var st:Statement;
		private var onConnectFlag:Boolean = false;
		
		private const HOST:String = "218.55.17.251";
		private const PORT:int = 3306;
		private const DB_ID:String = "root";
		private const DB_PW:String = "zinna1230";
		private const DB_NAME:String = "zinna_scdb";
		
		public function DBConnector()
		{
			if(_instance != null){ 
				throw new Error("Error: Singletons can only be instantiated via getInstance() method!");
			} 
		}
		
		public function onConnect():void
		{
			con = new Connection(HOST, PORT, DB_ID, DB_PW, DB_NAME);
			con.addEventListener(Event.CONNECT, onConnected);
			con.addEventListener(MySqlErrorEvent.SQL_ERROR, onError);
			con.addEventListener(Event.CLOSE, onClose);
			con.connect();
		}
		
		public static function getInstance():DBConnector{
			if(_instance == null)_instance = new DBConnector();
			
			return _instance;
		}
		
		private function onConnected(e:Event = null):void
		{
			st = con.createStatement();
			st.streamResults = true;
			onConnectFlag = true;
			FlexGlobals.topLevelApplication.onConnectHandler();
//			st.streamingInterval = 10000;
		}
		
		private function onClose(e:Event):void
		{
			con.disconnect();
		}
		
		public function executeQuery(qry:String, type:String):void
		{
			if(!onConnectFlag) return;
			var token:MySqlToken = st.executeQuery(qry);
			token.addEventListener(MySqlEvent.ROWDATA, function(e:MySqlEvent):void{newDataProvide(e, type)});
		}
		
		private function newDataProvide(e:MySqlEvent, type:String):void
		{
			var rs:ResultSet = e.resultSet;
			var newRows:ArrayCollection = rs.getRows(false, resultAc.length, (rs.size() - resultAc.length));
			resultAc.source = resultAc.source.concat( newRows.source );
			resultAc.refresh();
			returnResultHandler(resultAc, type);
		}
		
		private function returnResultHandler(ac:ArrayCollection, type:String):void
		{
			if(type == ApplicationModel.getInstance().TEST_QUERY)
			{
				ApplicationModel.getInstance().testAc = ac;
			}
		}
		
		private function onError(e:MySqlErrorEvent):void
		{
			Alert.show(e.text);
		}
	}
}